package com.navi.loaddata.job;

import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.repository.impl.MySqlRepositoryImpl;
import com.navi.loaddata.loadService.IEtlConfServices2;
import com.navi.loaddata.loadService.impl.defect.LoadAdefectService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * LoadAdefectData
 *
 * @author Matthew
 * @date 2018-07-14
 */
public class LoadAdefectData  implements Job {

  @Autowired
  private IEtlConfServices2 etlConfServices;
  @Autowired
  private LoadAdefectService loadAdefectService;
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    EtlConfD etlConfD = etlConfServices.getNewConf(context);
    if (null == etlConfD) {
      return;
    }
    etlConfD = etlConfServices.beginJob(etlConfD);
    if (StringUtils.isEmpty(etlConfD.getQueryMinute())) {
      return;
    }
    startEtl(etlConfD);

  }

  public void startEtl(EtlConfD etlConfD) {

    try {
      int count = loadAdefectService.loadAdefectDataMain(etlConfD);
      EtlConfDModel etlConf = etlConfServices.endJobOfModel(etlConfD);
      if (null == etlConf) {
        return;
      }
      String[] resMsg = {String.valueOf(count), "0", null};
      EtlConfDModel etlConfDModel;
      etlConfDModel = etlConfServices.endJobOfModel(etlConfD);
      if (null == etlConfDModel) {
        return;
      }
      etlConfServices.addHisOfModel(etlConfDModel, resMsg);
    } catch (ETLException2 e) {
      String[] errMsg = null;
      String err = e.getErrorCode().getErrorMsg();
      errMsg[0] = "0";
      errMsg[1] = "0";
      errMsg[2] = err;
      EtlConfDModel etlConfDModel = etlConfServices.endJobOfModel(etlConfD);
      if (null == etlConfDModel) {
        return;
      }
      etlConfServices.addHisOfModel(etlConfDModel, errMsg);

    }
    etlConfServices.endJob(etlConfD);
  }
}
